package com.commodity.servlet;

import com.alibaba.fastjson2.JSONArray;
import com.commodity.Service.InventoryService;
import com.commodity.Service.inventoryServiceImp.InventoryServiceImp;
import com.commodity.entity.Inventory;
import com.commodity.entity.InventoryData;
import com.commodity.entity.InventorySearchBean;
import com.commodity.utils.BeanFactory;
import com.commodity.utils.FormatMatch;
import com.commodity.utils.PaginateInfo;
import com.commodity.utils.ServletUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@WebServlet("/inventory/*")
public class InventoryServlet extends HttpServlet {
    InventoryService inventoryService = BeanFactory.getInstance(InventoryServiceImp.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String action = req.getPathInfo();//inventory/后的动作
        String method = req.getMethod().toLowerCase();//请求类型
        System.out.println(action + " " + method);
        if ("/list".equals(action)) {
            if ("get".equals(method)) {
                String count1 = req.getParameter("length");
                String warehouseId = req.getParameter("warehouseId");
                System.out.println("get请求里id值:"+warehouseId);
                req.setAttribute("warehouseId",warehouseId);
                int count;
                String[] commodityIdsFromCommodityList = null;
                if (count1!=null){
                    count = Integer.parseInt(count1);
                    if (count>0){
                        commodityIdsFromCommodityList = new String[count];
                        for (int i = 0; i < count; i++) {
                            commodityIdsFromCommodityList[i] = req.getParameter("commodityIdsFromCommodity"+i);
                        }
                    }
                    req.setAttribute("commodityIdsFromCommodityList",JSONArray.of(commodityIdsFromCommodityList));
                    req.getRequestDispatcher("/WEB-INF/jsp/inventory/listPart.jsp").forward(req, resp);
                }else {
                    req.getRequestDispatcher("/WEB-INF/jsp/inventory/list.jsp").forward(req, resp);
                }
            } else {
                list(req, resp);
            }

        } else if ("/add".equals(action)) {
            if ("get".equals(method)) {
                String error = (String) req.getSession().getAttribute("error");
                HttpSession session = req.getSession();
                String success = (String) session.getAttribute("success");
                if (StringUtils.hasText(success)){
                    req.setAttribute("success",success);
                    session.removeAttribute("success");
                }else if (StringUtils.hasText(error)) {
                    req.setAttribute("error", error);
                    req.getSession().removeAttribute("error");
                    Inventory inventory = (Inventory) req.getSession().getAttribute("inventory");
                    req.setAttribute("inventory", inventory);
                    req.getSession().removeAttribute("inventory");
                }
                System.out.println(action + " " + method);
                req.getRequestDispatcher("/WEB-INF/jsp/inventory/add.jsp").forward(req, resp);
            } else {
                add(req, resp);
            }
        } else if ("/delete".equals(action)) {
            delete(req, resp);
        } else if ("/edit".equals(action)) {
            if ("get".equals(method)) {
                String id = req.getParameter("id");
                HttpSession session = req.getSession();
                String success = (String) session.getAttribute("success");
                if (StringUtils.hasText(success)){
                    req.setAttribute("success",success);
                    session.removeAttribute("success");
                }else if(StringUtils.hasText(id)) {
                    Inventory inventory1 = inventoryService.findById(Integer.valueOf(id));
                    if (id == null) {
                        req.setAttribute("error", "要修改的学生信息不存在");
                    } else {
                        req.setAttribute("inventory", inventory1);
                    }
                } else {
                    req.setAttribute("error", "未指定修改的信息主键");
                }
                req.getRequestDispatcher("/WEB-INF/jsp/inventory/edit.jsp").forward(req, resp);
            } else {
                edit(req, resp);
            }
        }else if ("/load".equals(action)){
            List<Inventory> inventoryList = inventoryService.findAllWareHouseId();
            System.out.println(inventoryList);
            ServletUtils.renderJson(inventoryList,resp);
        }else if("/echart".equals(action)){
            if ("get".equals(method)){
                String id = req.getParameter("id");
                if (id!=""){
                    req.setAttribute("id",id);
                }
//                req.getRequestDispatcher("/WEB-INF/jsp/commodity/echarts.jsp").forward(req,resp);
                echart(req,resp);
            }
        }
    }


    private void list(HttpServletRequest req, HttpServletResponse resp) {

        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        int iPageNo = 1;
        int iPageSize = 10;
        if (StringUtils.hasText(pageNo)) {
            iPageNo = Integer.parseInt(pageNo);
        }
        if (StringUtils.hasText(pageSize)) {
            iPageSize = Integer.parseInt(pageSize);
        }
        PaginateInfo pi = new PaginateInfo(iPageNo, iPageSize);
        String[] commodityIdsFromCommodityList = req.getParameterValues("commodityIdsFromCommodityList1");
        String warehouseId1 = req.getParameter("warehouseId2");
        System.out.println("post中id1"+warehouseId1);
        List<Inventory> inventoryList = null;
        if (commodityIdsFromCommodityList==null){
            if (warehouseId1!=""){
                inventoryList = inventoryService.findByWarehouseId(warehouseId1,pi);
            }else{
                //获取请求参数
                String warehouseId = req.getParameter("warehouseId");
                String commodityId = req.getParameter("commodityId");
                String entryTimeFrom = req.getParameter("entryTimeFrom");
                String entryTimeTo = req.getParameter("entryTimeTo");

                InventorySearchBean isb = new InventorySearchBean();
                if (StringUtils.hasText(warehouseId)) {
                    isb.setWarehouseId(warehouseId);
                }

                if (StringUtils.hasText(commodityId)) {
                    isb.setCommodityId(commodityId);
                }
                if (StringUtils.hasText(entryTimeFrom)) {
                    isb.setEntryTimeFrom(LocalDate.parse(entryTimeFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                if (StringUtils.hasText(entryTimeTo)) {
                    isb.setEntryTimeTo(LocalDate.parse(entryTimeTo, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                inventoryList = inventoryService.findAll(isb, pi);
            }


        }else{
            inventoryList = inventoryService.findByCommodityIds(commodityIdsFromCommodityList,pi);
        }

        ServletUtils.renderJson(Map.of("pi", pi, "inventoryList", inventoryList), resp);

    }


    //add的post方法
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String warehouseId = req.getParameter("warehouseId");
        String commodityId = req.getParameter("commodityId");
        String inventory = req.getParameter("inventory");
        String entryTime = req.getParameter("entryTime");

        Inventory inventory1 = new Inventory();
        HttpSession session = req.getSession();
        String error = null;
        //后端校验
        if (!StringUtils.hasText(warehouseId)) {
            error = "仓库编号不可为空";
        }
        inventory1.setWarehouseId(warehouseId);
        if (!StringUtils.hasText(commodityId)) {
            if (error==null){
                error = "商品编号不可为空";
            }
        }
        inventory1.setCommodityId(commodityId);
        if (!StringUtils.hasText(inventory)) {
            if (error==null){
                error = "库存不可为空";
            }
        }
        Integer iInventory = null;
        if (inventory != "") {
            iInventory = Integer.valueOf(inventory);
            inventory1.setInventory(iInventory);
        }

        boolean isInteger = FormatMatch.isInteger(inventory);
        if (!isInteger){
            if (error==null){
                error = "库存数量格式错误";
            }
        }


        if (!StringUtils.hasText(entryTime)) {
            if (error==null){
                error = "入库时间不可为空";
            }
        }
        LocalDate entryTime1 = LocalDate.parse(entryTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        inventory1.setEntryTime(entryTime1);

        if (error != null) {
            session.setAttribute("error", error);
            session.setAttribute("inventory", inventory1);
            resp.sendRedirect(req.getContextPath() + "/inventory/add");
            return;
        }

        //调用service类进行保存
        boolean success = inventoryService.add(inventory1);
        if (success) {
            session.setAttribute("success","success");
            resp.sendRedirect(req.getContextPath() + "/inventory/add");
        } else {
            session.setAttribute("error", "添加库存信息失败,请联系管理员");
            session.setAttribute("inventory", inventory1);
            resp.sendRedirect(req.getContextPath() + "/inventory/add");
        }
    }

    //删除方法
    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        String[] ids = req.getParameterValues("ids");
        Integer[] intIds = Stream.of(ids).map(Integer::valueOf).toArray(Integer[]::new);
        int rows = inventoryService.delete(intIds);
        ServletUtils.renderJson(Map.of("success", true, "rows", rows), resp);
    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        System.out.println(id);
        Inventory inventory1 = inventoryService.findById(Integer.valueOf(id));
        if (inventory1 == null) {
            resp.sendRedirect(req.getContextPath() + "/inventory/edit");
            return;
        }
        //会话域
        HttpSession session = req.getSession();

        //修改业务
        String warehouseId = req.getParameter("warehouseId");
        String commodityId = req.getParameter("commodityId");
        String inventory = req.getParameter("inventory");
        String entryTime = req.getParameter("entryTime");
        String error = null;

        //后端校验
        if (!StringUtils.hasText(warehouseId)) {
            error = "仓库编号不可为空";
        }
        inventory1.setWarehouseId(warehouseId);
        if (!StringUtils.hasText(commodityId)) {
            error = "商品编号不可为空";
        }
        inventory1.setCommodityId(commodityId);
        if (!StringUtils.hasText(inventory)) {
            error = "库存不可为空";
        }
        Integer iInventory = null;
        if (inventory != "") {
            iInventory = Integer.valueOf(inventory);
            inventory1.setInventory(iInventory);
        }

        boolean isInteger = FormatMatch.isInteger(inventory);
        if (!isInteger){
            if (error==null){
                error = "库存数量格式错误";
            }
        }
        if (!StringUtils.hasText(entryTime)) {
            error = "入库时间不可为空";
        }
        LocalDate entryTime1 = LocalDate.parse(entryTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        inventory1.setEntryTime(entryTime1);

        if (error != null) {
            session.setAttribute("error", error);
            session.setAttribute("inventory", inventory1);
            resp.sendRedirect(req.getContextPath() + "/inventory/edit?id=" + id);
            return;
        }
        boolean success = this.inventoryService.update(inventory1);
        if (success) {
            session.setAttribute("success","success");
            resp.sendRedirect(req.getContextPath() + "/inventory/list");
        } else {
            session.setAttribute("error", "修改失败,请联系管理员或稍后再试");
            session.setAttribute("inventory", inventory1);
            resp.sendRedirect(req.getContextPath() + "/inventory/edit?id=" + id);
            return;
        }
    }

    private void echart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String commodityId = req.getParameter("commodityId");

        List<InventoryData> inventoryList = inventoryService.findByCommodityId(commodityId);
        String error = "";
        if (inventoryList==null){
            error = "该商品暂时没有库存";
        }

        req.setAttribute("incentoryList",JSONArray.of(inventoryList));
        req.getRequestDispatcher("/WEB-INF/jsp/commodity/echarts.jsp").forward(req,resp);
//        ServletUtils.renderJson(Map.of("inventoryData",inventoryList,"error",error),resp);
    }

}
